<?php
/*
 * 自动下载图片
 * 时间: 2016.02.24 
 */
use Org\Net\Http;
class DownloadPic{
	
	private $data;
	public function __construct($data){
		$this->localUrl = "./Public/uploads/images/Network/".date("Ymd")."/";
		$this->createDir($this->localUrl);
		$this->data = $data;
	}
	
	public function createDir($path){ 
		if (!file_exists($path)){ 
			$this->createDir(dirname($path)); 
			mkdir($path, 0777); 
		} 
	}
	
	public function work(){
		$data = $this->data;
		foreach($data as &$v){
			$v = $this->check($v);
		}
		return $data;
	}
	
	public function check($val){
		preg_match_all('/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|.png]))[\'|\"].*?[\/]?>/', $val, $imgArray);
		if(!empty($imgArray)){
			foreach($imgArray[1] as $key=>&$v){
				if(strpos($v,"http")!== false){
					$loaclfile = $this->getImage($v);
					$val = str_replace($v,$loaclfile,$val);
				}
			}
		}
		return $val;
	}
	
	private function getImage($img){
		$loaclfile = $this->AutoNaming($img);
		Http::curlDownload($img,$loaclfile);
		$loaclfile = ltrim($loaclfile, ".");
		return $loaclfile;
	}
	
	//自动命名
	private function AutoNaming($img,$name=""){
		$suffix = $this->getFileType($img);
		$filename = time().rand("1000","9999");
		return $this->localUrl.$date.$filename.".".$suffix;
	}
	
	//获取文件后缀类型
	private function getFileType($filename){
	  $type = substr($filename, strrpos($filename, ".")+1);
	  return $type;
	}
	
}
?>